package com.moonce.api.util;


import com.moonce.api.model.User;
import com.moonce.api.util.constant.Constant;
import com.moonce.api.util.constant.PlayLoad;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

@Component
public class JwtUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtil.class);

    @Value("${token.secret}")
    private static String profiles;

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public SecretKey generalKey() {
        String stringKey = profiles + Constant.JWT_SECRET;
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 创建jwt
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     * @throws Exception
     */
    public String createJWT(String id, String subject, long ttlMillis){
        SignatureAlgorithm hs256 = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        long expMillis = nowMillis + ttlMillis;
        Date now = new Date(nowMillis);
        Date exp = new Date(expMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(now)
                .setAudience(CommonUtils.longCastString(expMillis))//使用aud字段代替传至前台的时间戳
                .setSubject(subject)
                .setExpiration(exp)
                .signWith(hs256, key);
        return builder.compact();
    }

    /**
     * 解密jwt
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseJWT(String jwt) {
        SecretKey key = generalKey();
        return Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
    }


    /**
     * 生成subject信息
     * @param o
     * @return
     */
    public PlayLoad generalSubject(Object o) {
        PlayLoad playLoad = new PlayLoad();
        if (o instanceof User) {
            User employee = (User) o;
            playLoad.setSub(employee.getUsername());
            playLoad.setUid(employee.getUsername());
        }
        return playLoad;
    }

    public static void main(String[] args) {
//        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//        SecretKey key = new JwtUtil().generalKey();
//        PlayLoad playLoad = new PlayLoad();
//        Long exp = System.currentTimeMillis();
//        System.out.println(exp);
//        playLoad.setExp(exp);
//        playLoad.setUid(111111111111111L);
//        String str = Jwts.builder()
//                .setPayload(new Gson().toJson(playLoad))
////                .setExpiration(new Date())
//                .signWith(signatureAlgorithm,key).compact();
//        System.out.println(str);
//        str = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0OTE2NDEyODM3MTIsInVpZCI6MTExMTExMTExMTExMTEzfQ==.Se4TdxHUWLRqtiZtNwr1V4Je_yAykwNy9Zdu0oJ6y-8";
//        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(str).getBody();
//        if ((Long)claims.get("exp") <=System.currentTimeMillis()) {
//            System.out.println("false");
//        }
//        for (String s : claims.keySet()) {
//            System.out.println(s+":"+claims.get(s));
//        }
//        Date date = new Date(1492495209);
//        System.out.println(DateFormatUtils.format(date, Code.YYYY_MM_DD_HH_MM_SS));
//        long l = System.currentTimeMillis();
//        System.out.println(l);
//        Date date2 = new Date(l);
//        System.out.println(DateFormatUtils.format(date2, Code.YYYY_MM_DD_HH_MM_SS));
    }
}
